#pragma once

#include <iostream>
#include <string>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include"Log.hpp"
#include"Comm.hpp"
#include "InetAddr.hpp"

namespace SocketModule
{
    using namespace LogModule;

    class Socket;
    using SockPtr  = std::shared_ptr<Socket>;

    // 基类，规定创建socket套接字方法
    class Socket
    {
    public:
        virtual ~Socket() = default;
        virtual int SocketOrDie() = 0;
        virtual void SetSocketOpt() = 0;
        virtual bool BindOrDie(int port) = 0;
        virtual bool ListenOrDie() = 0;
        virtual SockPtr Accepter(InetAddr* client) = 0;
        virtual void Close() = 0;
        virtual int Recv(std::string* out) = 0;
        virtual int Send(const std::string& in) = 0;
        virtual int Fd() = 0;

        // 提供一个创建listensockfd的固定讨论
        void BuildTcpSocketMethod(int port) 
        {
            SocketOrDie();
            SetSocketOpt();
            BindOrDie(port);
            ListenOrDie();
        }
    };


    class TcpSocket : public Socket
    {
    public:
        TcpSocket():_sockfd(-1)
        {}
        TcpSocket(int sockfd):_sockfd(sockfd)
        {}
        virtual ~TcpSocket()
        {}
        virtual int SocketOrDie() override
        {
            _sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
            if(_sockfd < 0)
            {
                LOG(LogLevel::ERROR)<<"socket error";
                exit(SOCKET_ERR);
            }
            LOG(LogLevel::DEBUG)<<"socket create succeed, sockfd:"<<_sockfd;
            return 0;
        }
        virtual void SetSocketOpt() override
        {
            //保证我们服务器，异常断开可以立即重启，没有bind问题
            int opt = 1;
            int n = ::setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
            (void)n;
        }
        virtual bool BindOrDie(int port)
        {
            if(_sockfd == -1)   return false;
            // struct sockaddr_in local;
            // memset(&local, 0, sizeof(local));
            InetAddr addr(port);
            int n = ::bind(_sockfd, addr.NetAddr(), addr.NetAddrLen());
            if(n < 0)
            {
                LOG(LogLevel::ERROR)<<"bind error";
            }
            LOG(LogLevel::DEBUG)<<"bind create succeed, sockfd is:"<<_sockfd;
            return true;
        }
        virtual bool ListenOrDie()  override
        {
            if(_sockfd == -1)   return false;
            int n = ::listen(_sockfd, gbacklog);
            if(n < 0)
            {
                LOG(LogLevel::ERROR)<<"listen error";
                exit(LISTEN_ERR);
                return false;
            }
            LOG(LogLevel::DEBUG)<<"listen create succeed:"<<_sockfd;
            return true;
        }
        //1文件描述符 2 client info
        virtual SockPtr Accepter(InetAddr* client) override
        {
            sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int newsockfd = ::accept(_sockfd, (sockaddr*)(&peer), &len);
            if(newsockfd < 0)
            {
                LOG(LogLevel::WARING)<<"accept error";
                return nullptr;
            }
            client->SetAddr(peer, len);

            return std::make_shared<TcpSocket>(newsockfd);
        }
        virtual void Close() override
        {
            if(_sockfd == -1)   return;
            ::close(_sockfd);
        }

        virtual int Recv(std::string* out)  override
        {
            char buffer[1024];
            auto size = ::recv(_sockfd, buffer, sizeof(buffer)-1, 0);
            if(size > 0)
            {
                buffer[size] = 0;
                *out = buffer;
            }
            return size;
        }
        virtual int Send(const std::string& in) override
        {
            auto size = ::send(_sockfd, in.c_str(),in.size(), 0);
            return size;
        }
        virtual int Fd() override
        {
            return _sockfd;
        }
    private:
        int _sockfd;
    };

}

